﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;

using LongNet.Util;
namespace LongNet.Util.SqlServer
{
    /// <summary>
    /// 代码生成器
    /// </summary>
    public static class CodeProduce
    {
        private static string strconn = "";

        public static List<string> GenerateMode(string connectString, string strNameSpace)
        {
            List<string> result = new List<string>();
            DataSet ds = new DataSet();

            ds = SqlClass.GetDataSet("select * from sysobjects where xtype='u'").DataResult;

            DataView dv = ds.Tables[0].DefaultView;

            for (int i = 0; i < dv.Count; i++)
            {
                string name = dv[i]["name"].ToString();

                string id = dv[i]["id"].ToString();


                ProModel(id ,name, strNameSpace.Trim(), ref result);

            }
            return result;
        }

        static string GetType(string xtype)
        {

            return SqlClass.GetObject("select top 1 name from systypes where xtype='" + xtype + "'").ToString();
        }


        public static void ProModel(string tbname, string strNamespace, ref  List<string> result)
        {
            string strnamespace = strNamespace;
            if (strnamespace != "")
            {
                strnamespace = "." + strnamespace;
            }
            SqlDataReader dr = SqlClass.GetDataReader(" select columnName as name,type  ,length as size,columnDesc   from tableview where tableName='" + tbname + "'",false);
            tbname = tbname.ToUpper().Substring(0, 1) + tbname.Substring(1);
            // string str = "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\nusing System.Data.SqlClient;\n\n";
            string str = "using System;\n\n";
            str = str + "namespace Model" + strnamespace + "\r\n{\r\n[Serializable]\r\npublic class " + tbname + " \r\n{";
            int k = 0;
            // string strClass = "  \n private int _ID; public int ID\r\n{\r\nget{return _ID;}\r\nset{_ID=value;}\r\n} \n";
            string strClass = "";
            bool HasRecord = false;
            while (dr.Read())
            {
                HasRecord = true;
                string name = Convert.ToString(dr["name"]).Trim();
                name = name.ToUpper().Substring(0, 1) + name.Substring(1);
                string type = dr["type"].ToString();// GetType(Convert.ToString(dr["xtype"])).ToLower();
                string size = Convert.ToString(dr["size"]);
                string desc = "\r\n  /// <summary>\r\n" +
                             "   /// " + dr["columnDesc"].ToString() + "\r\n" +
                             "   /// </summary>\r\n";

                if (type == "int")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "tinyint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "smallint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "bigint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "varchar")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "nvarchar")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "nchar")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "char")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "text")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "ntext")
                {

                    //strClass = strClass +desc;strClass = strClass + " public string " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "datetime")
                {

                    // strClass = strClass +desc;strClass = strClass + " public DateTime " + name + ";\n";

                    strClass = strClass + " private DateTime _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public DateTime " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "float")
                {

                    // strClass = strClass +desc;strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "decimal")
                {

                    // strClass = strClass +desc;strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "numeric")
                {

                    // strClass = strClass +desc;strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "image")
                {
                    strClass = strClass + " private Image _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public Image " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "bit")
                {
                    strClass = strClass + " private bool _" + name + ";\r\n";
                    strClass = strClass + desc;
                    strClass = strClass + " public bool " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else
                {
                    //Response.Write("<br>Error:" + type + "--- 表" + tbname);
                    result.Add("Error:" + type + "--- 表" + tbname);
                }
                strClass = strClass + "\r\n";
                //SqlDbType.Float 

                k++;
            }
            dr.Close();
            //输出参数

            if (!HasRecord)
            {
                //Response.Write("<br>Error:该表没有任何字段- -表" + tbname);
                result.Add("Error:该表没有任何字段- -表" + tbname);
            }
            string strdir = "D:\\code\\model\\" + strnamespace.Replace(".", "") + "\\";
            if (!Directory.Exists(strdir))
            {
                Directory.CreateDirectory(strdir);
            }
            str = str + "\r\n" + strClass + "\n" + "\n}\r\n}\r\n";
            SaveStringToFile(str, strdir + tbname + ".cs");
            result.Add(strdir + tbname + ".cs");
            //  SaveStringToFile(str, Server.MapPath("app_code/" + tbname + ".txt"));
            // Response.Write(tbname + "<br>");
        }



        public static void ProModel(string id, string tbname, string strNamespace, ref  List<string> result)
        {

            string strnamespace = strNamespace;

            if (strnamespace != "")
            {
                strnamespace = "." + strnamespace;
            }
            SqlDataReader dr = SqlClass.GetDataReader("select name,xtype,length as size from syscolumns where id=" + id,false);
            tbname = tbname.ToUpper().Substring(0, 1) + tbname.Substring(1);
            string str = "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Data.SqlClient;\n\n";
            str = str + "namespace LongNet.Model" + strnamespace + "\r\n{\r\n[Serializable]\r\npublic class " + tbname + " \r\n{";
            int k = 0;
            // string strClass = "  \n private int _ID; public int ID\r\n{\r\nget{return _ID;}\r\nset{_ID=value;}\r\n} \n";
            string strClass = "";
            bool HasRecord = false;
            while (dr.Read())
            {
                HasRecord = true;
                string name = Convert.ToString(dr["name"]).Trim();
                name = name.ToUpper().Substring(0, 1) + name.Substring(1);
                string type = GetType(Convert.ToString(dr["xtype"])).ToLower();
                string size = Convert.ToString(dr["size"]);
                if (type == "int")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "tinyint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "smallint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "bigint")
                {
                    strClass = strClass + " private int _" + name + ";\r\n";
                    strClass = strClass + " public int " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "varchar")
                {

                    //strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "nvarchar")
                {

                    //strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "nchar")
                {

                    //strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "char")
                {

                    //strClass = strClass + " public string  " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "text")
                {

                    //strClass = strClass + " public string " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "ntext")
                {

                    //strClass = strClass + " public string " + name + ";\n";

                    strClass = strClass + " private string _" + name + ";\r\n";
                    strClass = strClass + " public string " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "datetime")
                {

                    // strClass = strClass + " public DateTime " + name + ";\n";

                    strClass = strClass + " private DateTime _" + name + ";\r\n";
                    strClass = strClass + " public DateTime " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "float")
                {

                    // strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "decimal")
                {

                    // strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "numeric")
                {

                    // strClass = strClass + " public double " + name + ";\n";

                    strClass = strClass + " private double _" + name + ";\r\n";
                    strClass = strClass + " public double " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "image")
                {

                    // strClass = strClass + " public double " + name + ";\n";

                    //strClass = strClass + " pivate object _" + name + ";\r\n";
                    //strClass = strClass + " public object " + name + "\r\n";
                    //strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    //strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set

                    strClass = strClass + " private Image _" + name + ";\r\n";
                    strClass = strClass + " public Image " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else if (type == "bit")
                {

                    strClass = strClass + " private bool _" + name + ";\r\n";
                    strClass = strClass + " public bool " + name + "\r\n";
                    strClass = strClass + " { get { return _" + name + ";}\r\n";//get
                    strClass = strClass + "   set { _" + name + "=value;}\r\n}";//set
                }
                else
                {
                    //Response.Write("<br>Error:" + type + "---" + id + "表" + tbname);
                    result.Add("Error:" + type + "---" + id + "表" + tbname);
                }
                strClass = strClass + "\r\n";
                //SqlDbType.Float 

                k++;
            }
            dr.Close();
            //输出参数

            if (!HasRecord)
            {
                result.Add("Error:该表没有任何字段-" + id + "-表" + tbname);

            }
            string strdir = "D:\\code\\model\\" + strnamespace.Replace(".", "") + "\\";
            if (!Directory.Exists(strdir))
            {
                Directory.CreateDirectory(strdir);
            }
            str = str + "\r\n" + strClass + "\n" + "\n}\r\n}\r\n";
            SaveStringToFile(str, strdir + tbname + ".cs");
            result.Add(strdir + tbname + ".cs");
            //  SaveStringToFile(str, Server.MapPath("app_code/" + tbname + ".txt"));
            // Response.Write(tbname + "<br>");
        }

        static void SaveStringToFile(string str, string filepath)
        {
            StreamWriter stw = new StreamWriter(filepath, false, System.Text.Encoding.Default);
            stw.Write(str);
            stw.Close();
        }

        public static List<string> GenerateDBAccess(string connectString, string strNameSpace)
        {
            List<string> result = new List<string>();
            DataSet ds = new DataSet();

            ds = SqlClass.GetDataSet("select * from sysobjects where xtype='u'").DataResult;

            DataView dv = ds.Tables[0].DefaultView;

            for (int i = 0; i < dv.Count; i++)
            {
                string name = dv[i]["name"].ToString();

                string id = dv[i]["id"].ToString();

                ProDBAccess(id, name, strNameSpace.Trim(), ref result);

            }

            return result;
        }
        static void ProDBAccess(string id, string tbname, string strNamespace, ref List<string> result)
        {
            //操作类
            string strnamespace = strNamespace;

            if (strnamespace != "")
            {
                strnamespace = "." + strnamespace;
            }

            SqlDataReader dr = SqlClass.GetDataReader("select name,xtype,length as size from syscolumns where id=" + id,false);
            tbname = tbname.ToUpper().Substring(0, 1) + tbname.Substring(1);
            string str = "using System;\nusing System.Data;\nusing System.Data.SqlClient;\r\nusing LongNet.Model" + strnamespace + ";\r\nusing LongNet.Util;\r\n";
            //string str = "using System;\nusing System.Data;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.UI.WebControls.WebParts;\nusing System.Web.UI.HtmlControls;\nusing System.Data.SqlClient;\r\nusing Model" + strnamespace + ";\r\nusing DBAccess;\r\nusing Util;\r\n";
            str = str + " namespace LongNet.DBAccess" + strnamespace + " \r\n{ [Serializable]\r\npublic class " + tbname + "D\n{";

            string markadd = " \n/// <summary>\n" +
                           " /// 添加表" + tbname + "记录并返回ID\n" +
                           " /// </summary>\n" +
                           " /// <param name=\"tb\">表" + tbname + "对象</param>\n" +
                           " /// <returns>返回ID</returns>\n";
            string markupdate = " \n /// <summary>\n" +
                                 " /// 修改表" + tbname + "记录并反回影响行数\n" +
                                 " /// </summary>\n" +
                                 " /// <param name=\"tb\">表" + tbname + "对象</param>\n" +
                                 " /// <returns>返回影响行数</returns>\n";
            string markdel = "  \n/// <summary>\n" +
                             " /// 通过ID删除记录\n" +
                             " /// </summary>\n" +
                             " /// <param name=\"id\">ID号</param>\n" +
                             " /// <returns>返回影响行数</returns>\n";

            string markdelWhere = "  \n/// <summary>\n" +
                            " /// 按条件删除记录\n" +
                            " /// </summary>\n" +
                            " /// <param name=\"strWhere\">删除的条件如：name='Jim'</param>\n" +
                            " /// <returns>返回影响行数</returns>\n";

            string markgettb = "  \n/// <summary>\n" +
                             " /// 通过ID返回对象" + tbname + "\n" +
                             " /// </summary>\n" +
                             " /// <param name=\"id\">ID号</param>\n" +
                             " /// <returns>返回" + tbname + "</returns>\n";
            string markgetdatareader = "  \n/// <summary>\n" +
                                       " /// 分页返回" + tbname + " datareader\n" +
                                       " /// </summary>\n" +
                                       " ///  <param name=\"pagesize\">返回记录数量</param>\n" +
                                       " ///  <param name=\"index\">当前第几页</param>\n" +
                                       " /// <returns>返回" + tbname + " 记录集</returns>\n";

            string add = markadd + "public  static Result  Add(SqlTransaction sqlTrans,Model" + strnamespace + "." + tbname + " tb)\n{\r\n ";
            string strSql = "string strSql=\" insert into [" + tbname + "](";
            string addField = "";
            string addPara = "";

            string updateNameID = "";

            string update = markupdate + "public  static Result Update (SqlTransaction sqlTrans ,Model" + strnamespace + "." + tbname + " tb)\n{\n  \n";
            string strUpdate = "string strSql =\"update [" + tbname + "] set ";
            string updateField = "";

            string gettb = markgettb + "public  static Model" + strnamespace + "." + tbname + "  GetModel( SqlTransaction  sqlTrans ,int id)\n{\n  Model" + strnamespace + "." + tbname + "  tb=null; \r\n";
            gettb = gettb + "  try{  DataSet ds = new DataSet();\r\n ds =  SqlHelper.ExecuteDataset(sqlTrans, CommandType.Text, \"select * from [" + tbname + "] where id=\"+id.ToString()); \n";
            gettb = gettb + " DataView dv = ds.Tables[0].DefaultView;\r\n                if (dv.Count > 0)      \r\n         {\r\n";
            gettb = gettb + " tb=new Model" + strnamespace + "." + tbname + "(); \n";

            string getModel = markgettb + "public  static Model" + strnamespace + "." + tbname + "  GetModel(SqlConnection sqlconn,int id)\n{\n  Model" + strnamespace + "." + tbname + "  tb=null;SqlDataReader dr=null ;  \r\n";
            getModel = getModel + "  try{ dr =  SqlHelper.ExecuteReader(sqlconn, CommandType.Text, \"select * from [" + tbname + "] where id=\"+id.ToString()); \n";
            getModel = getModel + " if(dr.Read())\n{ tb=new Model" + strnamespace + "." + tbname + "(); \n";

            string getModelsSqlconn = "  \n/// <summary>\n" +
                             " /// 通过条件返回对象" + tbname + "列表\n" +
                             " /// </summary>\n" +
                             " /// <param name=\"strWhere\">条件如name='aaa',小心注入攻击</param>\n" +
                             " /// <returns>返回" + tbname + "</returns>\r\n" +
                             "public static Model" + strnamespace + "." + tbname + "[] GetModels(SqlConnection sqlconn,string strWhere){\r\n" +
                             "try\r\n{\r\n" +
                              "string strSql = \"\"; if (strWhere == \"\") { strWhere = \"  1=1\"; }\r\n " +
                                 " strSql = \"select * from [" + tbname + "] Where \" + strWhere;\r\n " +
                                 "DataSet ds = SqlHelper.ExecuteDataset(sqlconn, CommandType.Text, strSql);    \r\n        DataView dv =ds.Tables[0].DefaultView;\r\n" +

                                 " int total = dv.Count;\r\n Model" + strnamespace + "." + tbname + "[] tbs = new Model" + strnamespace + "." + tbname + "[total];\r\n" +
                                 " for (int i = 0; i < dv.Count; i++) {  tbs[i] = new Model" + strnamespace + "." + tbname + "();";



            string getModelsSqlTrans = "  \n/// <summary>\n" +
                         " /// 通过条件返回对象" + tbname + "列表\n" +
                         " /// </summary>\n" +
                         " /// <param name=\"strWhere\">条件如name='aaa',小心注入攻击</param>\n" +
                         " /// <returns>返回" + tbname + "</returns>\r\n" +
                         "public static Model" + strnamespace + "." + tbname + "[] GetModels(SqlTransaction  sqlTrans ,string strWhere){\r\n" +
                         "try\r\n{\r\n" +
                          "string strSql = \"\"; if (strWhere == \"\") { strWhere = \"  1=1\"; }\r\n " +
                             " strSql = \"select * from [" + tbname + "] Where \" + strWhere;\r\n " +
                             "DataSet ds = SqlHelper.ExecuteDataset(sqlTrans, CommandType.Text, strSql);    \r\n        DataView dv =ds.Tables[0].DefaultView;\r\n" +

                             " int total = dv.Count;\r\n Model" + strnamespace + "." + tbname + "[] tbs = new Model" + strnamespace + "." + tbname + "[total];\r\n" +
                             " for (int i = 0; i < dv.Count; i++) {  tbs[i] = new Model" + strnamespace + "." + tbname + "();";

            string getModels = "";



            string para = "   SqlParameter[] sqlpar ={ \n ";
            string vals = "";
            int k = 0;
            //string strClass = "public class TB" + tbname + "\n{   \n public int ID;  \n";
            string strClass = "  \n  ";
            bool HasRecord = false;
            while (dr.Read())
            {
                HasRecord = true;
                string name = Convert.ToString(dr["name"]).Trim();
                name = name.ToUpper().Substring(0, 1) + name.Substring(1);
                string type = GetType(Convert.ToString(dr["xtype"]).Trim()).ToLower();
                string size = Convert.ToString(dr["size"]);

                if (name.ToLower() != "id")
                {
                    addField += "[" + name + "],";
                    addPara += "@" + name + ",";
                    updateField += name + "=@" + name + ",";
                }

                if (name.ToLower() == "id" && type == "int")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dr[\"" + name + "\"]);} \n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToInt32(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "int")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Int),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToInt32(dv[i][\"" + name + "\"]);}\r\n";

                }
                else if (type.ToLower() == "smallint")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt16(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.SmallInt),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt16(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToInt16(dv[i][\"" + name + "\"]);}\r\n";

                }
                else if (type == "bit")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToBoolean(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Bit),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToBoolean(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToBoolean(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "bigint")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.BigInt),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToInt32(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "tinyint")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.TinyInt),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToInt32(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToInt32(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "varchar")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.VarChar," + size + "),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }

                else if (type == "char")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Char," + size + "),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }
                else if (type == "nchar")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.NChar," + size + "),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }
                else if (type == "nvarchar")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.NVarChar," + size + "),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }


                else if (type == "text")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Text),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }
                else if (type == "ntext")
                {
                    getModel = getModel + "  tb." + name + "=Convert.ToString(dr[\"" + name + "\"]); \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.NText),\n";
                    gettb = gettb + "  tb." + name + "=Convert.ToString(dv[0][\"" + name + "\"]); \n";
                    getModels += "  tbs[i]." + name + " = Convert.ToString(dv[i][\"" + name + "\"]); \r\n";
                }
                else if (type == "float")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Float),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToDouble(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "decimal")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Decimal),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToDouble(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "numeric")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Decimal),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDouble(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToDouble(dv[i][\"" + name + "\"]);}\r\n";
                }
                else if (type == "datetime")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDateTime(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.DateTime),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDateTime(dv[0][\"" + name + "\"]);} \n";

                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToDateTime(dv[i][\"" + name + "\"]);}\r\n";

                }
                else if (type.ToLower() == "smalldatetime")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDateTime(dr[\"" + name + "\"]);} \n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.SmallDateTime),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " =Convert.ToDateTime(dv[0][\"" + name + "\"]);} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " = Convert.ToDateTime(dv[i][\"" + name + "\"]);}\r\n";

                }
                else if (type == "image")
                {
                    getModel = getModel + "    if (dr[\"" + name + "\"] != DBNull.Value){ tb." + name + " =(Image ) dr[\"" + name + "\"];} \n";
                    //   para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Binary),\n";
                    para = para + "                           new SqlParameter(\"@" + name + "\",SqlDbType.Image),\n";
                    gettb = gettb + "    if (dv[0][\"" + name + "\"] != DBNull.Value){ tb." + name + " = (Image ) dv[0][\"" + name + "\"] ;} \n";
                    getModels += "  if (dv[i][\"" + name + "\"] != DBNull.Value){tbs[i]." + name + " =  (Image ) dv[i][\"" + name + "\"] ;}\r\n";

                }
                else
                {
                    result.Add("Error:" + id + "-" + tbname + "-" + type);

                }
                //SqlDbType.Float 
                if (name.ToLower() != "id")
                {
                    vals = vals + "sqlpar[" + k.ToString() + "].Value=PublicClass.GetNullValue(tb." + name + ");\n";
                    k++;
                }
                else
                {
                    updateNameID = name;
                }
            }
            dr.Close();
            //输出参数



            if (!HasRecord)
            {
                result.Add("该表没有任何字段");

            }
            /*添加数据方法定义*/
            addField = addField.Substring(0, addField.Length - 1);
            addPara = addPara.Substring(0, addPara.Length - 1);

            strSql = strSql + addField + ")  \"\r\n+\" values(" + addPara + ")\"+\r\n\"; select SCOPE_IDENTITY() \";\r\n";

            add = add + strSql +
                "\r\n Result rs = new Result();\r\n" +
                "try\r\n{\r\n" + para.Substring(0, para.Length - 2) + " \r\n   };\n" +
                vals + "\n " +
                "rs.DataResult = SqlHelper.ExecuteDataset(sqlTrans, CommandType.Text, strSql, sqlpar);\r\n" +
                "if (rs.DataResult.Tables.Count > 0 && rs.DataResult.Tables[0].Rows.Count > 0 && !Convert.IsDBNull(rs.DataResult.Tables[0].Rows[0][0]))\r\n { \r\n rs.IsSuccess = true;\r\n }\r\n else\r\n { \r\n rs.IsSuccess = false;\r\n }\r\n }" +
                    "\r\ncatch(Exception ex){\r\n rs.IsSuccess = false ; \r\nrs.Msg = ex.Message; \r\nthrow ex;}" +
                    "\r\nfinally{}" +
                    "\r\nreturn rs;\r\n}\r\n";

            /*修改数据方法定义区*/
            updateField = updateField.Substring(0, updateField.Length - 1);
            strUpdate = strUpdate + updateField + " where id=@id\";";
            update = update + strUpdate + "\r\n   Result rs = new Result();\r\n try\r\n{\r\n" +
                para + "   new SqlParameter(\"@ID\",SqlDbType.Int)   };\n" +
                vals + " \r\nsqlpar[" + k.ToString() + "].Value=tb." + updateNameID + ";\r\n" +
               " int iflag = SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.Text, strSql, sqlpar);\r\n " +
                "if (iflag>0) { rs.IsSuccess = true; } else { rs.IsSuccess = false; } }\r\n" +
                " catch (Exception ex) { \r\nrs.IsSuccess = false; \r\nrs.Msg = ex.Message; \r\nthrow ex; \r\n}\r\n" +
                " finally { }\r\n" +
                " return rs;\r\n}\r\n";


            /*按ID删除*/
            string delete = markdel + "public static Result  Delete (SqlTransaction sqlTrans,int id)\n{ \n " +
                "string strSql=\"delete from [" + tbname + "] where id=\"+id.ToString();\r\n" +
                " Result rs = new Result();\r\n try\r\n{\r\n" +
                " int iflag = SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.Text, strSql, null);\r\n " +
                "  rs.IsSuccess = true;   }\r\n" +
                " catch (Exception ex) { \r\nrs.IsSuccess = false; \r\nrs.Msg = ex.Message; \r\nthrow ex; \r\n}\r\n" +
                " finally { }\r\n" +
                " return rs;\r\n}\r\n";

            /*按条件删除*/
            markdelWhere = markdelWhere + "\r\npublic static Result  Delete (SqlTransaction sqlTrans,string strWhere)\n{ \n " +
                "string strSql=\"\";\r\n" +
                 " Result rs = new Result();\r\n try\r\n{\r\n" +
                "if (strWhere.Trim() != \"\") { strSql = \"delete from [" + tbname + "]  where \" + strWhere; } else { rs.IsSuccess = false; rs.Msg = \"未传入删除条件\"; return rs; }" +
                " int iflag = SqlHelper.ExecuteNonQuery(sqlTrans, CommandType.Text, strSql, null);\r\n " +
                "  rs.IsSuccess = true;   }\r\n" +
                " catch (Exception ex) { \r\nrs.IsSuccess = false; \r\nrs.Msg = ex.Message; \r\nthrow ex; \r\n}\r\n" +
                " finally { }\r\n" +
                " return rs;\r\n}\r\n";


            //按ID查得某条记录
            gettb = gettb + "  \r\n}\r\n}catch (Exception ex){throw ex;}\r\nfinally{ }\r\nreturn tb;}\r\n";
            getModel = getModel + "  \r\n}\r\n}catch (Exception ex){throw ex;}\r\nfinally{dr.Close();dr.Dispose();}\r\nreturn tb;}\r\n";
            //返回model 列表

            getModelsSqlTrans = getModelsSqlTrans + getModels + "}\r\n return tbs;}catch (Exception ex){ throw ex;} }";

            getModelsSqlconn = getModelsSqlconn + getModels + "}\r\n return tbs;}catch (Exception ex){ throw ex;} }";



            //分页获取数据
            string strpage = markgetdatareader + "public static  Result  GetDataSet(SqlConnection sqlconn,int pagesize,int index)\n";
            strpage += "{\n";
            strpage += "int nextpage=pagesize*(index-1);\n" +
            " string strSql = \"select top \" + pagesize.ToString() + \" * from   [" + tbname.Replace("'", "").Trim() + "]  where id not in (select top \" + nextpage.ToString() + \" id from  [" + tbname.Replace("'", "").Trim() + "]  order by id desc) order by id desc\";\n" +
           " Result rs = new Result();\r\n try\r\n{\r\n" +
            " rs.DataResult = SqlHelper.ExecuteDataset(sqlconn, CommandType.Text, strSql); \r\n" +
            "if (rs.DataResult.Tables.Count > 0)" +
            "{ \r\n rs.IsSuccess = true;\r\n }\r\n else\r\n { \r\n rs.IsSuccess = false;\r\n }\r\n }" +
            "\r\ncatch(Exception ex){\r\n rs.IsSuccess = false ; \r\nrs.Msg = ex.Message; \r\nthrow ex;}" +
            "\r\nfinally{}" +
            "\r\nreturn rs;\r\n}\r\n";



            //获取全部数据
            string strGetAllData = "public static  Result  GetDataSet(SqlConnection sqlconn)\n";
            strGetAllData += "{\n";
            strGetAllData += " string strSql = \"select   * from   [" + tbname.Replace("'", "").Trim() + "]  order by id  \";\n" +
           " Result rs = new Result();\r\n try\r\n{\r\n" +
            " rs.DataResult = SqlHelper.ExecuteDataset(sqlconn, CommandType.Text, strSql); \r\n" +
            "if (rs.DataResult.Tables.Count > 0)" +
            "{ \r\n rs.IsSuccess = true;\r\n }\r\n else\r\n { \r\n rs.IsSuccess = false;\r\n }\r\n }" +
            "\r\ncatch(Exception ex){\r\n rs.IsSuccess = false ; \r\nrs.Msg = ex.Message; \r\nthrow ex;}" +
            "\r\nfinally{ }" +
            "\r\nreturn rs;\r\n}\r\n";

            //统计共有多少条数据
            string strCount = "public static Result Count(SqlConnection sqlConn)\n";
            strCount += "{\n" +
            " string strSql = \"select count(*)   from   [" + tbname.Replace("'", "").Trim() + "]\";\n" +
            " Result rs = new Result();\r\n try\r\n{\r\n" +
            " rs.DataResult = SqlHelper.ExecuteDataset(sqlConn, CommandType.Text, strSql); \r\n" +
            "if (rs.DataResult.Tables.Count > 0 && rs.DataResult.Tables[0].Rows.Count > 0)" +
            "{ \r\n rs.IsSuccess = true;\r\n }\r\n else\r\n { \r\n rs.IsSuccess = false;\r\n }\r\n }" +
            "\r\ncatch(Exception ex){\r\n rs.IsSuccess = false ; \r\nrs.Msg = ex.Message; \r\nthrow ex;}" +
            "\r\nfinally{ }" +
            "\r\nreturn rs;\r\n}\r\n";

            //string connstr = "\r\n public string connstr = Util.PublicClass.GetConnStr();";
            str = str + "\n" + add + "\n" + update + delete + markdelWhere + gettb + getModel + getModelsSqlconn + getModelsSqlTrans + strpage + strGetAllData + strCount + "\n}\r\n}";
            string strdir = "D:\\code\\DBAccess\\" + strnamespace.Replace(".", "") + "\\";
            if (!Directory.Exists(strdir))
            {
                Directory.CreateDirectory(strdir);
            }
            SaveStringToFile(str, strdir + tbname + "D.cs");
            result.Add(strdir + tbname + "D.cs");

        }
        public static List<string> GenerateBussiness(string connectString, string strNameSpace)
        {
            List<string> result = new List<string>();
            DataSet ds = new DataSet();
            ds = SqlClass.GetDataSet("select * from sysobjects where xtype='u'").DataResult;

            DataView dv = ds.Tables[0].DefaultView;

            for (int i = 0; i < dv.Count; i++)
            {
                string name = dv[i]["name"].ToString();

                string id = dv[i]["id"].ToString();


                ProBussiness(name, strNameSpace.Trim(), ref result);

            }
            return result;
        }

        static void ProBussiness(string tbname, string strNamespace, ref List<string> result)
        {

            // string str = "abc" + "\n" + "3333" + "\n" + " update + delete + markdelWhere + gettb + getModel + getModelsSqlconn + getModelsSqlTrans + strpage + strGetAllData + strCount" + "\n}\r\n334\r\n556\r\n}";
            string str = " using System;\r\n" +
    " using System.Collections.Generic;\r\n" +
    " using System.Linq;\r\n" +
    "using System.Text;\r\n" +
    "using System.Data.SqlClient;\r\n" +
    "using System.Data;\r\n" +
    "using System.Web;\r\n" +
    "using LongNet.Model." + strNamespace + ";\r\n" +
    "using LongNet.DBAccess." + strNamespace + ";\r\n" +
    "using LongNet.Util;\r\n" +

    " namespace LongNet.Bussiness." + strNamespace + "\r\n" +
    " {\r\n" +
       " public class " + tbname + "B\r\n" +
       "{\r\n" +

           " public static Result Add(Model." + strNamespace + "." + tbname + " m_" + tbname + ")\r\n" +
           "{\r\n" +

               "Result rs = new Result(); \r\n" +
               "SqlConnection sqlCon = new SqlConnection(SqlHelper.ConnectionString); \r\n" +
               "sqlCon.Open(); \r\n" +
               "Result rs1 = new Result(); \r\n" +
               "SqlTransaction SqlTran = sqlCon.BeginTransaction(); \r\n" +

              " try \r\n" +
               "{ \r\n" +
                  " rs = DBAccess." + strNamespace + "." + tbname + "D.Add(SqlTran, m_" + tbname + "); \r\n" +

                  " if (rs.IsSuccess) \r\n" +
                  " { \r\n" +
                      " SqlTran.Commit(); \r\n" +
                   "} \r\n" +
                  " else \r\n" +
                   "{ \r\n" +
                       "SqlTran.Rollback(); \r\n" +
                  " } \r\n" +
               "} \r\n" +
               "catch (Exception ex) \r\n" +
              " { \r\n" +
                   "SqlTran.Rollback(); \r\n" +
                  " rs.Msg = ex.Message; \r\n" +
                   "throw ex; \r\n" +
               "} \r\n" +
               "finally \r\n" +
               "{ \r\n" +
                   "if (sqlCon.State == System.Data.ConnectionState.Open) \r\n" +
                   "{ \r\n" +
                      " sqlCon.Close(); \r\n" +
                   "} \r\n" +

                  " sqlCon.Dispose(); \r\n" +
                   "SqlTran.Dispose(); \r\n" +
               "} \r\n" +
               "return rs; \r\n" +
           "} \r\n" +

           "public static Result Update(Model." + strNamespace + "." + tbname + " m_" + tbname + ") \r\n" +
           "{ \r\n" +
              " SqlConnection sqlCon = new SqlConnection(SqlHelper.ConnectionString); \r\n" +

              " sqlCon.Open(); \r\n" +

               "SqlTransaction SqlTran = sqlCon.BeginTransaction(); \r\n" +

              " Result rs = new Result(); \r\n" +

               "try \r\n" +
              " { \r\n" +
                  " rs = DBAccess." + strNamespace + "." + tbname + "D.Update(SqlTran, m_" + tbname + "); \r\n" +

                  " if (rs.IsSuccess) \r\n" +
                   "{ \r\n" +
                      " SqlTran.Commit(); \r\n" +
                  " } \r\n" +
    "else\r\n" +
                  " { \r\n" +
                      " SqlTran.Rollback(); \r\n" +
                   "} \r\n" +
              " } \r\n" +
               "catch (Exception ex) \r\n" +
              " { \r\n" +
                   "SqlTran.Rollback(); \r\n" +

                  " rs.Msg = ex.Message; \r\n" +

                   "throw ex; \r\n" +
               "} \r\n" +
               "finally \r\n" +
               "{ \r\n" +
                 "  if (sqlCon.State == System.Data.ConnectionState.Open) \r\n" +
                  " { \r\n" +
                    "   sqlCon.Close(); \r\n" +
                   "} \r\n" +
                   "SqlTran.Dispose(); \r\n" +

                   "sqlCon.Dispose(); \r\n" +
               "} \r\n" +
               "return rs; \r\n" +
           "} \r\n" +



           "public  static Result Delete(Model." + strNamespace + "." + tbname + " m_" + tbname + ") \r\n" +
           "{ \r\n" +
             "  return " + tbname + "B.Delete(m_" + tbname + ".Id); \r\n" +
           "} \r\n" +
          " public static Result Delete(int Id) \r\n" +
           "{ \r\n" +
             "  SqlConnection sqlCon = new SqlConnection(SqlHelper.ConnectionString); \r\n" +

              " sqlCon.Open(); \r\n" +

               "SqlTransaction SqlTran = sqlCon.BeginTransaction(); \r\n" +

              " Result rs = new Result(); \r\n" +

               "try \r\n" +
               "{ \r\n" +
                "   rs = DBAccess." + strNamespace + "." + tbname + "D.Delete(SqlTran, Id); \r\n" +

                 "  if (rs.IsSuccess) \r\n" +
                  " { \r\n" +
                    "   SqlTran.Commit(); \r\n" +
                   "} \r\n" +
                   " else \r\n" +
                   "{ \r\n" +
                    "   SqlTran.Rollback(); \r\n" +
                   "} \r\n" +
               "} \r\n" +
               "catch (Exception ex) \r\n" +
               "{ \r\n" +
                "   SqlTran.Rollback(); \r\n" +

                 "  rs.Msg = ex.Message; \r\n" +

                  " throw ex; \r\n" +
               "} \r\n" +
               "finally \r\n" +
               "{ \r\n" +
                "   if (sqlCon.State == System.Data.ConnectionState.Open) \r\n" +
                 "  { \r\n" +
                  "     sqlCon.Close(); \r\n" +
                   "} \r\n" +
                   "SqlTran.Dispose(); \r\n" +

                   "sqlCon.Dispose(); \r\n" +
               "} \r\n" +
               "return rs; \r\n" +
           "} \r\n" +


           "/// <summary> \r\n" +
           "/// 获取分页的" + tbname + "记录列表 \r\n" +
           "/// </summary> \r\n" +
           "/// <param name=\"iCurrentPage\">当前页</param> \r\n" +
           "/// <param name=\"iPageSize\">每页记录数量</param> \r\n" +
           "/// <param name=\"strSelectColumns\">要选择的列</param> \r\n" +
           "/// <param name=\"strWhere\">Where查询条件</param> \r\n" +
           "/// <param name=\"strOrderBy\">要排序的Sql</param> \r\n" +
           "/// <returns></returns> \r\n" +
           "public static Result GetPaginationData(int iCurrentPage, int iPageSize, string strSelectColumns, string strWhere, string strOrderBy) \r\n" +
           "{ \r\n" +
             "  if (string.IsNullOrEmpty(strSelectColumns)) \r\n" +
              " { \r\n" +
                "   strSelectColumns = \"" + tbname + ".* \"; \r\n" +
               "} \r\n" +
               "if (string.IsNullOrEmpty(strOrderBy)) \r\n" +
               "{ \r\n" +
                 "  strOrderBy = \"Order by Id\"; \r\n" +
               "} \r\n" +
               "return SqlClass.ExecPagenationSP( \" " + tbname + " \", strWhere, strSelectColumns, iCurrentPage, iPageSize, strOrderBy, \"\"); \r\n" +
           "} \r\n" +
           "/// <summary> \r\n" +
           "/// 获取分页的" + tbname + "记录列表 \r\n" +
           "/// </summary> \r\n" +
           "/// <param name=\"iCurrentPage\">当前页</param> \r\n" +
           "/// <param name=\"iPageSize\">每页记录数量</param> \r\n" +
           "/// <param name=\"strSelectColumns\">要选择的列</param> \r\n" +
           "/// <param name=\"strWhere\">Where查询条件</param> \r\n" +
           "/// <returns></returns> \r\n" +
           "public static Result GetPaginationData(int iCurrentPage, int iPageSize, string strSelectColumns, string strWhere) \r\n" +
           "{ \r\n" +
             "  return GetPaginationData(iCurrentPage, iPageSize, strSelectColumns, strWhere, null); \r\n" +
           "} \r\n" +
           "/// <summary> \r\n" +
           "/// 获取分页的" + tbname + "记录列表 \r\n" +
           "/// </summary> \r\n" +
           "/// <param name=\"iCurrentPage\">当前页</param> \r\n" +
           "/// <param name=\"iPageSize\">每页记录数量</param> \r\n" +
           "/// <param name=\"strSelectColumns\">要选择的列</param> \r\n" +
           "/// <returns></returns> \r\n" +
           "public static Result GetPaginationData(int iCurrentPage, int iPageSize, string strSelectColumns) \r\n" +
           "{ \r\n" +
           "    return GetPaginationData(iCurrentPage, iPageSize, strSelectColumns, null); \r\n" +
           "} \r\n" +
           "/// <summary> \r\n" +
           "/// 获取分页的" + tbname + "记录列表 \r\n" +
          " /// </summary> \r\n" +
           "/// <param name=\"iCurrentPage\">当前页</param> \r\n" +
           "/// <param name=\"iPageSize\">每页记录数量</param> \r\n" +
           "/// <param name=\"strSelectColumns\">要选择的列</param> \r\n" +
           "/// <returns></returns> \r\n" +
           "public static Result GetPaginationData(int iCurrentPage, int iPageSize) \r\n" +
           "{ \r\n" +
            "   return GetPaginationData(iCurrentPage, iPageSize, null); \r\n" +
           "} \r\n" +
           "/// <summary> \r\n" +
           "/// 获取分页的" + tbname + "记录列表 \r\n" +
           "/// </summary> \r\n" +
           "/// <returns></returns> \r\n" +
           "public static Result GetPaginationData() \r\n" +
           "{ \r\n" +
            "   return GetPaginationData(0, 0); \r\n" +
           "} \r\n" +


           "public static Model." + strNamespace + "." + tbname + " GetModel(int id) \r\n" +
           "{ \r\n" +
             "  SqlConnection sqlCon = new SqlConnection(SqlHelper.ConnectionString); \r\n" +
              " try \r\n" +
               "{ \r\n" +
                "   sqlCon.Open(); \r\n" +
                 "  Model." + strNamespace + "." + tbname + " m = DBAccess." + strNamespace + "." + tbname + "D.GetModel(sqlCon, id); \r\n" +
                  " sqlCon.Close(); \r\n" +
                   "return m; \r\n" +
               "} \r\n" +
               "catch (Exception ex) \r\n" +
               "{ \r\n" +
                "   sqlCon.Close(); \r\n" +
                 "  throw ex; \r\n" +
               "} \r\n" +
               "finally \r\n" +
               "{ \r\n" +
                "   if (sqlCon.State == ConnectionState.Open) sqlCon.Close(); \r\n" +
                 "  sqlCon.Dispose(); \r\n" +
               "} \r\n" +
           "} \r\n" +


           "/// <summary>\r\n" +
            "/// 按条件删除记录\r\n" +
            "/// </summary>\r\n" +
            "/// <param name=\"strWhere\">删除的条件如：name='Jim'</param>\r\n" +
            "/// <returns>返回影响行数</returns>\r\n" +

           " public static Result Delete(string strWhere)\r\n" +
            "{\r\n" +
                "Result res = new Result();\r\n" +
                "SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString);\r\n" +
                "conn.Open();\r\n" +
               " SqlTransaction sqlTrans = conn.BeginTransaction();\r\n" +
               " try\r\n" +
                "{\r\n" +
                    "res = DBAccess." + strNamespace + "." + tbname + "D.Delete(sqlTrans, strWhere);\r\n" +
                   " if (res.IsSuccess)\r\n" +
                    "{\r\n" +
                       " sqlTrans.Commit();\r\n" +
                   " }\r\n" +
                   " else \r\n" +
                    "{ \r\n" +
                        "sqlTrans.Rollback(); \r\n" +
                    "} \r\n" +
                "} \r\n" +
               " catch (Exception e)\r\n" +
               " {\r\n" +
                    "sqlTrans.Rollback();\r\n" +
                    "res.Msg = e.Message;\r\n" +
                   " throw e;\r\n" +
                "}\r\n" +
                "finally\r\n" +
                "{\r\n" +
                    "if (conn.State == System.Data.ConnectionState.Open)\r\n" +
                    "{\r\n" +
                        "conn.Close();\r\n" +
                    "}\r\n" +
                    "conn.Dispose();\r\n" +
                    "sqlTrans.Dispose();\r\n" +

                "}\r\n" +
                "return res;\r\n" +
           " }\r\n" +

           " /// <summary>\r\n" +
             "/// 通过条件返回对象" + tbname + "s列表\r\n" +
             "/// </summary>\r\n" +
             "/// <param name=\"strWhere\">条件如name='aaa',小心注入攻击</param>\r\n" +
             "/// <returns>返回Building</returns>\r\n" +
             "public static Model." + strNamespace + "." + tbname + " [] GetModels(string strWhere)\r\n" +
             "{\r\n" +
                 " Model." + strNamespace + "." + tbname + " [] m_" + tbname + "s = null;\r\n" +
                 "Result res = new Result();\r\n" +
                " SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString);\r\n" +
                 "conn.Open();\r\n" +
                 "try\r\n" +
                 "{\r\n" +
                     "m_" + tbname + "s =  DBAccess." + strNamespace + "." + tbname + "D.GetModels(conn, strWhere);\r\n" +
                     "res.IsSuccess = true;\r\n" +
                 "}\r\n" +
                 "catch (Exception e)\r\n" +
                 "{\r\n" +
                    " res.Msg = e.Message;\r\n" +
                     "res.IsSuccess = false;\r\n" +
                     "throw e;\r\n" +
                " }\r\n" +
                " finally\r\n" +
                 "{\r\n" +
                     "if (conn.State == System.Data.ConnectionState.Open)\r\n" +
                     "{\r\n" +
                         "conn.Close();\r\n" +
                     "}\r\n" +
                     "conn.Dispose();\r\n" +
                 "}\r\n" +
                 "return m_" + tbname + "s;\r\n" +
            " }\r\n" +
     "  } \r\n" +
    "} \r\n";

            string strdir = "D:\\code\\Bussiness\\" + strNamespace.Replace(".", "") + "\\";
            if (!Directory.Exists(strdir))
            {
                Directory.CreateDirectory(strdir);
            }
            SaveStringToFile(str, strdir + tbname + "B.cs");
            result.Add(strdir + tbname + "B.cs");
        }

    }
}
